package com.example.mediademo.repository;

import com.example.mediademo.entity.Media;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.param.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;

@Repository
public interface MediaRepository extends JpaRepository<Media, Integer> {
    // 根据单个媒体编号查找
    Media findByKeynumber(String keynumber);
    
    // 根据多个媒体编号查找
    List<Media> findByKeynumberIn(List<String> keynumbers);
    
    // 根据类型查找并分页
    Page<Media> findByType(int type, Pageable pageable);
    
    // 联合查询，包含媒体类型名称
    @Query("SELECT m.city as city, m.keynumber as keynumber, t.name as typeName " +
           "FROM Media m JOIN MediaType t ON m.type = t.id " +
           "WHERE m.keynumber = ?1")
    Map<String, Object> findMediaDetails(String keynumber);
    
    // 分页查询所有媒体（包含类型名称）
    @Query("SELECT m.city as city, m.keynumber as keynumber, t.name as typeName " +
           "FROM Media m JOIN MediaType t ON m.type = t.id")
    Page<Map<String, Object>> findAllMediaDetails(Pageable pageable);
    
    // 条件查询（支持可选的类型和多个编号）
    @Query("SELECT m.city as city, m.keynumber as keynumber, t.name as typeName " +
           "FROM Media m JOIN MediaType t ON m.type = t.id " +
           "WHERE (:type is null OR m.type = :type) " +
           "AND (:keynumbers is null OR m.keynumber IN (:keynumbers))")
    Page<Map<String, Object>> findMediaByConditions(
        @Param("type") Integer type, 
        @Param("keynumbers") List<String> keynumbers, 
        Pageable pageable
    );
}
